package com.piece.admin.controller.system;

import com.piece.admin.model.TbSysPost;
import com.piece.admin.service.TbSysPostService;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.support.response.Select;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.log.client.dto.UserDTO;
import com.piece.core.log.config.UserContextHolder;
import com.piece.core.web.controller.FrameWorkController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = {"岗位管理"})
@RequestMapping("/api/system/post")
public class SysPostController extends FrameWorkController {

    @Resource
    private TbSysPostService tbSysPostService;

    @PostMapping("/list")
    @AclPermission(code = "system:post:view")
    @ApiOperation(value = "查询岗位列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysPostService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "system:post:view")
    @ApiOperation(value = "查询岗位", notes = "查询岗位分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysPostService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "system:post:view")
    @ApiOperation(value = "生成岗位表单数据")
    @ApiImplicitParam(name = "id", value = "岗位主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        TbSysPost post = new TbSysPost();
        if (id != 0) {
            post = tbSysPostService.findById(id);
        }
        return success(post);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "system:post:add,system:post:edit")
    @ApiOperation(value = "保存岗位表单数据")
    @ApiImplicitParam(value = "岗位表单数据", dataTypeClass = TbSysPost.class, type = "body")
    public AjaxResponse save() {
        TbSysPost post;
        try {
            Long id = Convert.toLong(getRequest().getParameter("postId"));
            if (null != id) {
                post = tbSysPostService.findById(id);
            } else {
                post = new TbSysPost();
            }
            initDB(post);
            setDefaultInfo(post);
            tbSysPostService.insertOrUpdate(post);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "system:post:delete")
    @ApiOperation(value = "删除岗位")
    @ApiImplicitParam(name = "ids", value = "岗位ID集合")
    public AjaxResponse delete() {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            tbSysPostService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @PostMapping("/select")
    @ApiOperation(value = "查询岗位下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "查询分页条件", dataTypeClass = Select.class, type = "body"),
            @ApiImplicitParam(name = "selected", value = "已选岗位ID"),
            @ApiImplicitParam(name = "Q_postName_S_LK", value = "岗位名称")
    })
    public AjaxResponse select() {
        String selected = getRequest().getParameter("selected");
        QueryTable queryTable = initSelect("Q_postName_S_LK");
        DataTable dataTable = tbSysPostService.findPage(queryTable);
        if (StringUtil.isNotEmpty(selected)) {
            selected = FrameWorkConstants.SPLIT_PARAM + selected + FrameWorkConstants.SPLIT_PARAM;
        }
        return success(tableToSelect(dataTable, selected));
    }

    private void setDefaultInfo(TbSysPost post) {
        UserDTO user = UserContextHolder.get();
        if (null == post.getPostId()) {
            post.setCreateBy(user.getId());
            post.setCreateTime(new Date());
        }
        post.setUpdateBy(user.getId());
        post.setUpdateTime(new Date());
    }

    private Select tableToSelect(DataTable dataTable, String selected) {
        Select select = Select.builder().build();
        List<TbSysPost> postList = dataTable.getData();
        List<Select.Entity> entityList = postList.stream().map(post -> {
            return select.new Entity(Convert.toStr(post.getPostId()), Convert.toStr(post.getPostName()));
        }).filter(entity -> {
            if (StringUtil.isNotEmpty(selected)) {
                if (selected.indexOf(FrameWorkConstants.SPLIT_PARAM + entity.getId() + FrameWorkConstants.SPLIT_PARAM) != -1) {
                    return true;
                }
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        select.setTotal(dataTable.getRecordsTotal());
        select.setData(entityList);
        return select;
    }
}
